package com.finance.cooperate.data.service.impl;

import com.finance.cooperate.common.utils.DateUtils;
import com.finance.cooperate.dao.entity.primary.Apply;
import com.finance.cooperate.dao.entity.primary.Borrowing;
import com.finance.cooperate.dao.local.scope.CooperateRequestScope;
import com.finance.cooperate.dao.repository.primary.ApplyRepository;
import com.finance.cooperate.dao.repository.primary.BorrowingRepository;
import com.finance.cooperate.data.service.ApplyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;

/**
 * @ClassName ApplyServiceImpl
 * @Description TODO
 * @Author shen
 * @Date 2023/8/10 21:29
 * @Modify ...
 */
@Slf4j
@Service
public class ApplyServiceImpl implements ApplyService {

    @Autowired
    private ApplyRepository applyRepository;

    @Autowired
    private CooperateRequestScope requestScope;

    @Autowired
    private BorrowingRepository borrowingRepository;

    @Override
    public String getUidByApplyId(String applyId) {

        Optional<Apply> optional = applyRepository.findById(applyId);

        if (optional.isPresent()) {

            Apply apply = optional.get();

            Date lastSubmitTime = DateUtils.addMinute(apply.getSubmitTime(), 30);

            // 临时缓存首贷进件时间：
            requestScope.setFirstLastSubmitTime(DateUtils.addMinute(apply.getSubmitTime(), 30));

            Long loanNum = requestScope.getLoanNum();

            String userId = apply.getUserId();

            if (loanNum > 1) {
                // 这里计算进件时间时，要区分首复贷
                Borrowing lastBorrowing = borrowingRepository.getLastBorrowing(userId, loanNum);

                if (lastBorrowing != null && lastBorrowing.getPayoffTime() != null) {
                    lastSubmitTime = DateUtils.addMinute(lastBorrowing.getPayoffTime(), 30);
                }

            }


            // 同时缓存相关信息
            requestScope.setPackageName(apply.getPackageName());

            requestScope.setLastSubmitTime(lastSubmitTime);

            return userId;

        }

        return null;
    }

    @Override
    public String getLastSubmitTime(String uid) {
        Date lastSubmitTime = requestScope.getLastSubmitTime();

        return DateUtils.toStr(lastSubmitTime);
    }


}
